package com.pro.common.api.sitecontent.model.response;

import com.pro.common.api.enums.init.EnumCurrency;
import com.pro.common.api.exception.BusinessException;
import com.pro.common.api.sitecontent.model.db.CurrencyExchangeRate;
import com.pro.common.api.sitecontent.model.dto.CurrencyExchangeRateKey;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Data
public class CurrencyExchangeRateContainer {

    public CurrencyExchangeRateContainer(List<CurrencyExchangeRate> activeList) {
        rateMap = activeList.stream().collect(Collectors.toMap(
                o -> new CurrencyExchangeRateKey(o.getFromCurrency(), o.getToCurrency()), CurrencyExchangeRate::getRate));
    }

    private Map<CurrencyExchangeRateKey, BigDecimal> rateMap;

    // 汇率换算
    public BigDecimal exchange(EnumCurrency fromCurrency, EnumCurrency toCurrency,BigDecimal fromNum) {
        return fromNum.multiply(getRate(fromCurrency, toCurrency));
    }
    public BigDecimal getRate(EnumCurrency fromCurrency, EnumCurrency toCurrency) {
        if (fromCurrency == null || toCurrency == null) {
            throw new BusinessException("获取汇率异常", fromCurrency, toCurrency);
        }
        if (fromCurrency.equals(toCurrency)) {
            return BigDecimal.ONE;
        }
        BigDecimal rate = rateMap.get(new CurrencyExchangeRateKey(fromCurrency, toCurrency));
        if (rate == null) {
            BigDecimal rateRevert = rateMap.get(new CurrencyExchangeRateKey(toCurrency, fromCurrency));
            if (rateRevert != null) {
                rate = BigDecimal.ONE.divide(rateRevert, 6, RoundingMode.HALF_UP);
            }
        }
        if (rate == null) {
            throw new BusinessException("获取汇率异常", fromCurrency, toCurrency);
        }
        return rate;
    }
}
